import React, { Component } from 'react'
import { _getLocation, _setLocation } from '../../utils/index'
export default class Commentinput extends Component {
	state = {
		username: '',
		content: '',
		stamp: '',
	}
	componentDidMount() {
		this.setState({
			username: _getLocation('name'),
		})
		this.input.focus() // 实现加载获取焦点
	}

	handleUsernameChange = (e) => {
		this.setState({
			username: e.target.value,
			stamp: Date.now(),
		})
	}
	handleContentChange = (e) => {
		this.setState({
			content: e.target.value,
			stamp: Date.now(),
		})
	}
	handleSubmit = () => {
		if (this.props.onSubmit) {
			const { username, content, stamp } = this.state
			this.props.onSubmit({ username, content, stamp })
		}
		this.setState({ content: '', stamp: '' })
	}
	// 失焦事件
	handleBlur = (e) => {
		_setLocation('name', e.target.value)
	}
	render() {
		return (
			<div className="comment-input">
				<div className="comment-field">
					<span className="comment-field-name">用户名：</span>
					<div className="comment-field-input">
						<input
							value={this.state.username}
							onChange={this.handleUsernameChange}
							onBlur={this.handleBlur}
							ref={(input) => {
								this.input = input
							}}
						/>
					</div>
				</div>
				<div className="comment-field">
					<span className="comment-field-name">评论内容：</span>
					<div className="comment-field-input">
						<textarea
							value={this.state.content}
							onChange={this.handleContentChange}
						/>
					</div>
				</div>
				<div className="comment-field-button">
					<button onClick={this.handleSubmit}>发布</button>
				</div>
			</div>
		)
	}
}
